package ldh.im.fxgui.controller.sub;

import com.jfoenix.controls.JFXDialog;
import javafx.beans.property.BooleanProperty;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import ldh.im.fxbase.data.pojo.ImSession;
import ldh.im.fxbase.service.MessageService;
import ldh.im.fxbase.service.ImSessionService;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.component.ImStage;
import ldh.im.fxgui.controller.IndependentController;
import ldh.im.fxgui.controller.MessageSessionController;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.fxgui.util.UserHeadImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * 消息-》会话(p2p)-》消息栏->设置
 */
public class SessionUserSettingController extends IndependentController implements Initializable {

    private static final Logger LOGGER = LoggerFactory.getLogger(SessionUserSettingController.class);

    @FXML private Label messageHistoryLabel;
    @FXML private ImageView ownerHeadImageView;
    @FXML private CheckBox messageDisturbCheckBox;
    @FXML private CheckBox messageTopCheckBox;

    private ImSession currentImSession;
    private MessageSessionController messageSessionController;
    private BooleanProperty settingPaneShowProperty;

    public void setParams(ImSession imSession, MessageSessionController messageSessionController, BooleanProperty settingPaneShowProperty) {
        this.currentImSession = imSession;
        this.messageSessionController = messageSessionController;
        this.settingPaneShowProperty = settingPaneShowProperty;

        if (imSession.isP2p()) {
            Image image = UserHeadImageUtil.getHeadImage(ImCacheFactory.getInstance().getUser(imSession.getToUserId()).getHeadImg());
            ownerHeadImageView.setFitHeight(40);
            ownerHeadImageView.setFitWidth(40);
            ownerHeadImageView.setImage(image);

            String userId = UiUtil.getLoginImUser().getUserId();
            if (imSession.getFromUserId().compareTo(imSession.getToUserId()) >= 0) {
                messageDisturbCheckBox.setSelected(!imSession.isDisturb());
                messageTopCheckBox.setSelected(imSession.isTop());
            } else {
                messageDisturbCheckBox.setSelected(!imSession.isDisturb2());
                messageTopCheckBox.setSelected(imSession.isTop2());
            }
        }

        bindSettingEvent();
    }

    @FXML
    public void openMessageHistoryPane(MouseEvent mouseEvent) {
        String fxml = "/fxml/sub/HistoryMessagePane.fxml";
        RegionUtil.FxmlBean<VBox, HistoryMessageController> fxmlBean = SoftMapUtil.getCache(fxml);
        if (fxmlBean == null) {
            fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource(fxml));
        }
        fxmlBean.getController().setImSession(currentImSession);
        ImStage stage = new ImStage(600, 700);
        Scene scene = stage.getCurrentScene();
        scene.getStylesheets().add(this.getClass().getResource("/css/var.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/bootstrapfx.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/message-dialog.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/scrollbar.css").toExternalForm());
        scene.getStylesheets().add(this.getClass().getResource("/css/pagination.css").toExternalForm());
        stage.setContent(fxmlBean.getNode());
        stage.setTitle(currentImSession.getName());
        stage.show();
    }

    @FXML
    public void showAddUserPane(ActionEvent actionEvent) {
        RegionUtil.FxmlBean<Pane, AddUserToGroupController> fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/sub/AddUserToGroupPane.fxml"));
        JFXDialog dialog = DialogUtil.show(getDialogRoot(), fxmlBean.getNode(), false);
        dialog.setPrefSize(500, 400);
        fxmlBean.getController().setDialog(dialog);
        fxmlBean.getController().setCurrentImSession(currentImSession);
    }

    @FXML
    public void cleanChatContent(ActionEvent actionEvent) {
        Task<Boolean> cleanTask = new Task() {

            @Override
            protected Object call() throws Exception {
                String userId = UiUtil.getLoginImUser().getUserId();
                MessageService messageService = BeanFactory.getInstance().getBean(MessageService.class);
                messageService.cleanMessage(userId, currentImSession.getId());
                return true;
            }
        };
        ThreadPoolUtil.submitTask(cleanTask);
        cleanTask.setOnSucceeded(s->{
            UiUtil.uiRefresh();
            DialogUtil.showSuccess(getDialogRoot(), "清理成功");
        });
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        Cursor cursor = messageHistoryLabel.getCursor();
        messageHistoryLabel.setOnMouseEntered(e->{
            messageHistoryLabel.setCursor(Cursor.HAND);
        });
        messageHistoryLabel.setOnMouseExited(e->{
            messageHistoryLabel.setCursor(cursor);
        });
    }

    private boolean isError = false;
    private void bindSettingEvent() {
        messageDisturbCheckBox.selectedProperty().addListener((l, o, n)->{
            if (o == n) return;
            if (isError) {
                isError = false;
                return;
            }
            String userId = UiUtil.getLoginImUser().getUserId();

            ImSessionService imSessionService = BeanFactory.getInstance().getBean(ImSessionService.class);
            Task task = imSessionService.disturbSession(userId, currentImSession, n.booleanValue());
            task.setOnFailed(e->{
                DialogUtil.alert("错误", "会话免打扰失败");
                isError = true;
                messageDisturbCheckBox.setSelected(o);
            });
        });

        messageTopCheckBox.selectedProperty().addListener((l, o, n)->{
            if (o == n) return;
            if (isError) {
                isError = false;
                return;
            }
            String userId = UiUtil.getLoginImUser().getUserId();

            ImSessionService imSessionService = BeanFactory.getInstance().getBean(ImSessionService.class);
            Task task = imSessionService.topSession(userId, currentImSession, n.booleanValue());
            task.setOnSucceeded(e-> {
                if (messageSessionController != null) {
                    messageSessionController.reloadMessageSession(currentImSession);
                }
            });
            task.setOnFailed(e->{
                DialogUtil.alert("错误", "会话置顶失败");
                isError = true;
                messageTopCheckBox.setSelected(o);
            });
        });
    }
}
